package com.googlecode.slm.sping;



import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.googlecode.slm.domain.web.UserNode;
import com.googlecode.slm.log.Log;
import com.googlecode.slm.log.LogFactory;
import com.googlecode.slm.service.SecurityService;
import com.googlecode.slm.util.CONSTANTS;
import com.googlecode.slm.web.BasicControler;

/**
 * 安全认证系统
 * 
 * @author liguangjian
 *
 */
public class SecurityHandlerInterceptor extends HandlerInterceptorAdapter{
	
	protected Log log = LogFactory.getLog(SecurityHandlerInterceptor.class);
	
	
    @Autowired
    @Qualifier(value = "securityService")
	private SecurityService securityService;
	
	
	public SecurityService getSecurityService() {
		return securityService;
	}


	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}


	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		boolean tagBool = true;
		if (handler instanceof BasicControler){
			BasicControler basic = (BasicControler) handler;
			if (basic.isAttestation()){
				String name = handler.getClass().getName();
				HttpSession session = request.getSession();
				UserNode object = (UserNode) session.getAttribute(CONSTANTS.SESSION_USER_LGON);
				if (object==null){
					tagBool = false;
					//request.setAttribute("info", "用户登陆超时!");
					setJsp(request, response, "用户登陆超时!");
				} else {
					if (securityService.getClassGard(object.getGrade(), name)){
						tagBool = true;
					} else {
						tagBool = false;
						//request.setAttribute("info", "用户没有受根该功能");
						setJsp(request, response, "用户没有受根该功能");
					}
				}
			} else {
				tagBool = true;
			}
		} else {
			log.error("控制类"+handler.getClass().getName()+"没有继承"+BasicControler.class.getName());
			tagBool = false;
		}
		return tagBool;
	}
	
	private void setJsp(HttpServletRequest request, HttpServletResponse response, String info){
		try {
			//String path = request.getContextPath()+CONSTANTS.PAGE_ERROR_JSP;
			//String path = request.getContextPath();
			//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+CONSTANTS.PAGE_ERROR_JSP;
			response.setContentType("text/html; charset=utf-8");
			response.sendRedirect(request.getContextPath()+CONSTANTS.PAGE_ERROR_JSP+"?info="+info);
			//System.out.println(basePath);
			//RequestDispatcher dispatcher = request.getRequestDispatcher(basePath); 
			//dispatcher.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
